import { PageContainer } from '@ant-design/pro-components';
import { Attachments, AttachmentsProps, Bubble, BubbleProps, Sender } from '@ant-design/x';
import { useRef, useState } from 'react';
import { CloudUploadOutlined, LinkOutlined, UserOutlined } from '@ant-design/icons';
import { Button, Flex, GetProp, GetRef, Result } from 'antd';
import ChatMessage from '@/components/ChatMessage';
import { fetchData } from '@/pages/chat/utils';

type ExtractFunc<T> = T extends (...args: any) => any ? T : never;
const getPlaceholderFn = (
  inlinePlaceholder: ReturnType<ExtractFunc<AttachmentsProps['placeholder']>>,
) => {
  return (type: 'inline' | 'drop') =>
    type === 'drop'
      ? {
          title: 'Drop file here',
        }
      : inlinePlaceholder;
};
export default () => {
  const listRef = useRef<GetRef<typeof Bubble.List>>(null);
  const [messageLoading, setMessageLoading] = useState<boolean>(false);
  const [text, setText] = useState('');
  const [messageList, setMessageList] = useState<BubbleProps[]>([]);
  const [open, setOpen] = useState<boolean>(false);

  const [items, setItems] = useState<GetProp<AttachmentsProps, 'items'>>([]);
  const [filePaths, setFilePaths] = useState<string[]>([]);

  const sharedAttachmentProps: AttachmentsProps = {
    items,
    onChange: ({ fileList,file }) => {
      setItems(fileList);
      if (file.status === 'uploading') {
        return;
      }
      setFilePaths([
        ...fileList.filter(file=>file.status==='done').map(file=>file.response)
      ])
      setText(fileList.length+"");
    },
  };

  const onSend = (data: string) => {
    setMessageLoading(true);
    setText('');
    let lastMessage: BubbleProps = {
      content: '',
      loading: true,
      avatar: { icon: <UserOutlined />, style: { background: '#fde3cf' } },
      messageRender: (text) => <ChatMessage content={text} />,
    };
    let newMessageList: BubbleProps[] = [
      ...messageList,
      {
        content: data,
        placement: 'end',
        avatar: { icon: <UserOutlined />, style: { background: '#87d068' } },
        messageRender: (text) => <ChatMessage content={text} />,
      },
    ];
    setMessageList([...newMessageList, lastMessage]);
    fetchData(
      {
        content:data,
        filePaths:filePaths.join(','),
      },
      (result) => {
        lastMessage = {
          ...lastMessage,
          loading: false,
          content: lastMessage?.content + result,
          messageRender: (text) => <ChatMessage content={text} />,
        };
        setMessageList(() => [...newMessageList, lastMessage]);
      },
      () => {
        setMessageLoading(false);
      },
    ).then((r) => {});
  };
  const headerNode = (
    <Sender.Header open={open} onOpenChange={() => setOpen(!open)}>
      <Flex vertical align="center" gap="small">
        <Attachments
          action="http://localhost:8080/api/file/upload"
          withCredentials
          name="file"
          {...sharedAttachmentProps}
          onRemove={() => {
            console.log('aaaa');
          }}
          placeholder={getPlaceholderFn(
            <Result
              title="支持 pdf, doc, xlsx, ppt, txt, image 文件"
              icon={<CloudUploadOutlined />}
              extra={<Button type="primary">选择文件</Button>}
              style={{ padding: 0 }}
            />,
          )}
        />
      </Flex>
    </Sender.Header>
  );
  return (
    <PageContainer>
      <Bubble.List
        ref={listRef}
        style={{ height: window.innerHeight - 400, maxHeight: window.innerHeight - 400 }}
        items={messageList}
      />
      <div style={{ height: 24 }} />
      <Sender
        header={headerNode}
        prefix={
          <Button
            type="text"
            icon={<LinkOutlined />}
            onClick={() => {
              setOpen(!open);
            }}
          />
        }
        value={text}
        loading={messageLoading}
        onChange={setText}
        onSubmit={(value) => {
          onSend(value);
        }}
        allowSpeech
      />
    </PageContainer>
  );
};
